
#include "EchoServer.h"
#include "Logging.h"

#include <unistd.h>

using namespace muduo;

EchoServer::EchoServer(muduo::EventLoop* pMainLoop, 
                       const muduo::InetAddress& listenAddr)
    : server_(threadNum, listenAddr, "EchoServer", true, pMainLoop)
{
    TcpServer::newConnectionCallback_ = std::bind(&EchoServer::newConnection, 
                                                 this, std::placeholders::_1);
                                         
    TcpServer::rcvMessageCallback_    = std::bind(&EchoServer::rcvMessage, 
                                                 this, 
                                                 std::placeholders::_1, 
                                                 std::placeholders::_2, 
                                                 std::placeholders::_3); 
}

void EchoServer::start()
{
    server_.start();
}

void EchoServer::join()
{
    server_.joinThread();
}

void EchoServer::newConnection(const muduo::TcpLinkSPtr& conn)
{
    //muduo::LOG_INFO("EchoServer - %s -> %s is %s",
    //                conn->peerAddress().toIpPort().c_str(),
    //                conn->localAddress().toIpPort().c_str(),
    //                ((conn->connected() ? "UP" : "DOWN")));
}

void EchoServer::delConnection(const muduo::TcpLinkSPtr& conn)
{

}

void EchoServer::rcvMessage(const muduo::TcpLinkSPtr& conn,
                            muduo::Buffer* buf, muduo::Timestamp time)
{
    std::string msg(buf->retrieveAllAsString());
    muduo::LOG_INFO("received %d bytes from %s", msg.size(), conn->name().c_str());
    conn->send(msg);
}


